package com.example.rpc_core.loadbalance.impl;

import com.example.rpc_core.loadbalance.LoadBalancer;
import com.example.rpc_core.model.ServiceInfo;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class ConsistentHashLoadBalancer implements LoadBalancer {

    //构建虚拟节点数
    private final int VIRTUAL_NODE_SIZE = 50;
    //在线程中创建虚拟节点
    private final TreeMap<Integer, ServiceInfo> virtualNodeMap = new TreeMap<>();
    @Override
    public ServiceInfo select(Map<String, Object> requestParams, List<ServiceInfo> serviceInfoList) {
        if (serviceInfoList.isEmpty()){
            return null;
        }
        virtualNodeMap.clear();
        //创建虚拟hash环
        for (ServiceInfo serviceInfo:serviceInfoList) {
            for (int i=0;i<VIRTUAL_NODE_SIZE;i++) {
                int hash=getHash(serviceInfo.getServiceAddress()+"#"+i);
                virtualNodeMap.put(hash,serviceInfo);
            }
        }

        int hash=getHash(requestParams);
        Map.Entry<Integer, ServiceInfo> entry = virtualNodeMap.ceilingEntry(hash);
        if (entry==null){
            entry = virtualNodeMap.firstEntry();
        }

        return entry.getValue();
    }

    public int getHash(Object key) {
        return key.hashCode();
    }
}
